<template>
    <div class="dashboard-container" >
      <el-upload
          class="upload-demo"
          :on-change="handleChange"
          :show-file-list="false"
          :auto-upload="false"
          accept=".csv,.xlsx,.xls"
          action="#"
      >
        <el-button type="primary" size="small">选择文件</el-button>
        <div slot="tip" class="el-upload__tip">只能选择csv,xls.xlsx文件</div>

        <el-button type="success" size="small" @click.stop.prevent="uploadUrls">上传</el-button>

        <el-button type="primary" @click.stop.prevent="exportTable">导出</el-button>

      </el-upload>

      <el-table :data="tableData" stripe style="width: 100%" ref="table" >
        <el-table-column prop="longUrl" label="长链接"/>
        <el-table-column prop="shortUrl" label="短链接"/>
<!--        <el-table-column prop="remark" label="备注" />-->
<!--        <el-table-column prop="status" label="状态" />-->
      </el-table>
    </div>
</template>
<script>

import {arrayContains} from '@/utils/util'
import * as XLSX from "xlsx";
import { batchCreate } from '../../api/shortUrl'
import dayjs from "dayjs";
import store from "@/store";

export default {
        components: {

        },
        data() {
            return {
              tableData:[],
            }
        },
        watch: {

        },
        computed: {
            superAdmin() {
                return arrayContains(this.$store.state.user.roles, "SuperAdmin");
            },
            admin() {
              return arrayContains(this.$store.state.user.roles, "Manager") || arrayContains(this.$store.state.user.roles, "SuperAdmin")
            }
        },
        created() {
        },
        beforeDestroy() {
            this.destroy();
        },

        methods: {
          handleChange(file) {
            const fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
            this.tableData = [];
            if (fileType === 'xlsx' || fileType === 'xls') {
              const reader = new FileReader();
              reader.onload = (e) => {
                const data = new Uint8Array(e.target.result);
                const workbook = XLSX.read(data, { type: 'array' });
                const firstSheetName = workbook.SheetNames[0];
                const worksheet = workbook.Sheets[firstSheetName];
                const dataArray = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
                console.info(dataArray)
                if (dataArray != null && dataArray.length > 1) {
                  for (let i = 1; i < dataArray.length; i++) {
                      let data = dataArray[i];
                      this.tableData.push({
                        "longUrl": data[0]
                      })
                  }
                }
              };
              reader.readAsArrayBuffer(file.raw);
            } else if (fileType === 'csv') {
              const reader = new FileReader();
              reader.onload = (e) => {
                const text = e.target.result;
                this.parseCSV(text);
              };
              reader.readAsText(file.raw);
            } else {
              this.$message.error('请上传Excel或者CSV文件');
            }
          },
          parseCSV(csvString) {
            const lines = csvString.split('\n');
            if (lines.length > 0) {
              this.csvHeaders = lines[0].split(',');
              let dataLines = lines.slice(1).map(line => line.split(','));
              for (let i = 0; i < dataLines.length; i++) {
                this.tableData.push({
                  "longUrl": dataLines[i][0]
                })
              }
            } else {
              this.csvHeaders = [];
              this.tableData = [];
            }
          },
          uploadUrls() {
            let batchNo = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss') + "_" + store.state.user.id
                let uploadData = [];
            for (let i = 0; i < this.tableData.length; i++) {
              let item = this.tableData[i];
              uploadData.push({
                "url": item["longUrl"],
                "remark": batchNo,
                "name": "",
              });
            }
            let that = this;
            batchCreate(uploadData).then(dataResponse => {
              let convertList = dataResponse.data;
              that.tableData = [];
              for (let i = 0; i < convertList.length; i++) {
                that.tableData.push({
                  "longUrl": convertList[i].longUrl,
                  "shortUrl": convertList[i].shortUrl
                  // "remark": convertList[i].remark,
                  // "status": convertList[i].status,
                })
              }
            })
          },
          exportTable() {
            const tableData = this.$refs.table.store.states.data;

            // 将数据转换为worksheet对象
            const worksheet = XLSX.utils.json_to_sheet(tableData);

            // 创建工作簿对象并将worksheet添加到工作簿
            const workbook = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

            // 将工作簿转换为二进制数据
            const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' });

            // 字符串转ArrayBuffer的辅助函数
            function s2ab(s) {
              const buf = new ArrayBuffer(s.length);
              const view = new Uint8Array(buf);
              for (let i = 0; i < s.length; i++) {
                view[i] = s.charCodeAt(i) & 0xff;
              }
              return buf;
            }

            // 创建Blob对象
            const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });

            // 创建下载链接并模拟点击下载
            const downloadLink = document.createElement('a');
            downloadLink.href = URL.createObjectURL(blob);
            downloadLink.download = 'table.xlsx'; // 下载文件名
            document.body.appendChild(downloadLink);
            downloadLink.click();

            // 下载完成后移除下载链接和释放URL对象
            setTimeout(() => {
              document.body.removeChild(downloadLink);
              URL.revokeObjectURL(downloadLink.href);
            }, 200);
          }
        }
    }
</script>

<style lang="scss" scoped>
 .dashboard {
   &-container {
     margin: 0 20px;

     .el-form-item {
       margin-bottom: 15px;
     }

   }
 }
</style>
